package com.carkeeper.system.service.impl;

import com.carkeeper.system.dao.DepartmentDao;
import com.carkeeper.system.dao.EmployeeDao;
import com.carkeeper.system.dao.RoleDao;
import com.carkeeper.system.dao.UserDao;
import com.carkeeper.system.pojo.Employee;
import com.carkeeper.system.service.AdminService;
import com.carkeeper.system.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author pengjinxiong
 * @version 1.0
 * @date 2020/11/26 9:42
 */
/*登录*/
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private RoleDao roleDao;


    @Override
    public Map login(String username, String password) {
        //查询数据库是否有该用户
        Employee employee = new Employee();
        employee.setUsername(username);
        employee.setPassword(password);
        employee.setAccountStatus("1");
        Employee employee1 = employeeDao.selectOne(employee);
        if (employee1 == null) {
            return null;
        }
        //存在验证密码
        boolean login = password.equals(employee1.getPassword());
        if (!login) {

            return null;
        }
        //创建token
        Map<String, Object> info = new HashMap();
        info.put("username", username);
        String id = UUID.randomUUID().toString();//设置唯一编号
        String subject = username;//主题
        String token = JwtUtil.createJWT(id, subject, null);
        info.put("uid",id);
        //登陆时间
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String format = f.format(new Date());
        info.put("time", format);
        //所属部门
        String departmentId = employee1.getDepartmentId();
        String departmentName = departmentDao.selectByPrimaryKey(departmentId).getName();
        info.put("department", departmentName);
        //角色
        Long employeeId = employee1.getId();
        List<String> employeeName = employeeDao.findNameByEmployeeId(employeeId);
        info.put("roles", employeeName);
        redisTemplate.boundValueOps(id).set(token, 3600, TimeUnit.SECONDS);


        return info;

    }
}
